package br.ufrj.neg.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
import org.apache.velocity.tools.view.VelocityViewServlet;

import br.ufrj.neg.usuario.bean.UsuarioBean;

public class UploadLogoNegociacaoAction extends VelocityViewServlet{

	private static final long serialVersionUID = -1502095409248120929L;
	//private static Logger log = Logger.getLogger("rootLogger");
//	private static final String TMP_DIR_PATH = "c:\\tmp";
//	private File tmpDir;
	private static final String DESTINATION_DIR_PATH ="/imagens/logos/temp";
	private File destinationDir;
 
	@Override
	public void init() throws ServletException {
		
		super.init();
//		tmpDir = new File(TMP_DIR_PATH);
//		if(!tmpDir.isDirectory()) {
//			throw new ServletException(TMP_DIR_PATH + " is not a directory");
//		}
		String realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
		destinationDir = new File(realPath);
		if(!destinationDir.isDirectory()) {
			throw new ServletException(DESTINATION_DIR_PATH+" is not a directory");
		}
 
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		
		try {

			String caminho = null;
			String tipo = null;
			
			UsuarioBean usuario = (UsuarioBean) request.getSession().getAttribute("usuarioBean");
			
			DiskFileItemFactory  fileItemFactory = new DiskFileItemFactory ();
			fileItemFactory.setSizeThreshold(1*1024*1024); //1 MB
			//fileItemFactory.setRepository(tmpDir);
			
			
			boolean isMultipart = ServletFileUpload.isMultipartContent(request);
			
			if (isMultipart)
			{
				ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
				
				List items = uploadHandler.parseRequest(request);
				Iterator itr = items.iterator();
				while(itr.hasNext()) {
					FileItem item = (FileItem) itr.next();
					
					if(item.isFormField()) {
													
						if(item.getFieldName().equals("tipoLogo")){
							 tipo =item.getString("UTF8");
						}
						
					} else if(!item.getName().equals("")){
																		
						caminho = usuario.getId()+"_"+tipo+"_"+item.getName();
						
						File file = new File(destinationDir,caminho);
						item.write(file);
				
					}
					
				}
			}else{ //O ajax uploader costuma utilizar este!
				
				tipo = request.getParameter("tipoLogo");
				caminho = usuario.getId()+"_"+tipo+"_"+request.getHeader("X-File-Name");
				InputStream is = request.getInputStream();
				FileOutputStream fos = new FileOutputStream(new File(destinationDir,caminho));
	            IOUtils.copy(is, fos);
				
			}
			
			PrintWriter out = response.getWriter();
			
			JSONObject jsonO = new JSONObject();			
			jsonO.put("success","true");
			jsonO.put("nome",caminho);
			jsonO.put("tipo",tipo);
	
			out.print(jsonO);
			
			
			
			
		}catch(FileUploadException ex) {
			PrintWriter out = response.getWriter();
			
			JSONObject jsonO = new JSONObject();			
			jsonO.put("success","false");
			jsonO.put("error", ex.getMessage());
			out.print(jsonO);
		
			ex.printStackTrace();
		}catch (Exception e) {
			PrintWriter out = response.getWriter();
			
			JSONObject jsonO = new JSONObject();			
			jsonO.put("success","false");
			jsonO.put("error", e.getMessage());
			out.print(jsonO);
		
			e.printStackTrace();
		}
	}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
	
			doPost(request,response);
	}
	
	
}
